package fpt.edu.vn.action;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fpt.edu.vn.dao.AddnewDao;
import fpt.edu.vn.dao.TopicsDao;
import fpt.edu.vn.model.Activityhistorys;
import fpt.edu.vn.model.Favorites;
import fpt.edu.vn.model.Provinces;
import fpt.edu.vn.model.Ratetopics;
import fpt.edu.vn.model.Reportspams;
import fpt.edu.vn.model.Topicimages;
import fpt.edu.vn.model.Topics;
import fpt.edu.vn.util.sendEmail;

/* 
 * DetailAction.java 
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class DetailAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private int topicId;
	private int districtId;
	private List<Object> detailsList;
	private List<Topicimages> images;
	private List<Topics> sameDistrict;
	private List<Object> checkOwnerTopic;
	private List<Object> checkAdmin;
	private List<Object> email;
	private int isOwner;
	private int isAdmin;
	private String Username;
	private Activityhistorys activityhistory = new Activityhistorys();
	private List<Object> universitiesList;
	private List<Object> markertsList;
	private List<Object> parksList;
	private List<Object> busList;
	private List<Object> rate;
	// Các tin đã xem
	private List<Object> recentView;

	private List<Provinces> provinces;

	private int userId;

	private int rateValue;

	private List<Topics> status;

	private int isHidden;

	private Ratetopics rateTopic = new Ratetopics();
	private Favorites fav = new Favorites();
	AddnewDao adddao = new AddnewDao();
	private sendEmail send = new sendEmail();
	private Reportspams reportSpam = new Reportspams();

	private String spamdescreption;

	public String getUsername() {
		return Username;
	}

	public void setUsername(String username) {
		Username = username;
	}

	// For SessionAware
	Map<String, Object> session;

	private TopicsDao dao = new TopicsDao();

	public String execute() {

		String displayNamess = "";
		String email = "";
		String ipaddress = "";
		Integer usersId = 0;
		session = ActionContext.getContext().getSession();
		session.put("exitFV", 0);
		if (session.containsKey("ipaddress")) {
			ipaddress = (String) session.get("ipaddress");
		}
		if (session.containsKey("displayNamess")) {
			displayNamess = (String) session.get("displayNamess");
			email = (String) session.get("emailss");
			usersId = (Integer) session.get("userIdss");
			if (dao.checkExitFav(topicId, usersId).size() < 1) {
				session.put("exitFV", 0);
			} else {
				session.put("exitFV", 1);
			}
			// get email, userid to compare with user login
			checkOwnerTopic = dao.checkOwnerTopic(email, topicId);
			checkAdmin = dao.checkAdmin(email);
			if (checkAdmin.size() < 1) {
			} else {
				setIsAdmin(1);
			}
			if (checkOwnerTopic.size() < 1) {
			} else {
				setIsOwner(1);
			}

		}
		if (email.equalsIgnoreCase("")) {
			email = "Guest";
		}
		boolean t = dao.checkExistActivityhistorys(ipaddress, topicId);
		if (t == false) {
			if (dao.checkExistActivityhistorys(ipaddress, topicId)) {
			} else {
				dao.updateViewNum(topicId);
			}
		}
		String displayNameAddToHistory = "";
		if ("".equals(displayNamess) || displayNamess == null) {
			setUsername(null);
			displayNameAddToHistory = "Guest";
		} else {
			setUsername(displayNamess);
			displayNameAddToHistory = displayNamess;

		}
		if (topicId == 0) {
			return NONE;
		} else {
			this.detailsList = dao.detail(topicId);
			if (detailsList.size() < 1) {
				return NONE;
			} else {
				this.status = dao.checkStatusTopic(topicId);
				String title_ = status.get(0).getTitle();
				int districtId_ = status.get(0).getDistrictId();
				if (status.get(0).getStatusTopicId() == 1) {
					setIsHidden(0);
					activityhistory.setActivityTypeId(1);
					activityhistory.setIpAddress(ipaddress);
					activityhistory.setUserName(email);
					activityhistory.setTopicId(topicId);
					activityhistory.setTitle(title_);
					activityhistory.setDistrictId(districtId_);
					dao.add(activityhistory);

					this.sameDistrict = dao.topicSameDistrict(districtId,
							topicId);
					this.recentView = dao.listRecentView(ipaddress);
					this.images = dao.image(topicId);
					this.universitiesList = dao.listUniversity(districtId);
					this.parksList = dao.listParks(districtId);
					this.markertsList = dao.listMarkets(districtId);
					this.rate = dao.getRate(topicId);
					this.busList = dao.listBus(districtId);
					this.provinces = dao.listProvinces();
				} else {
					if (isAdmin == 1 || isOwner == 1) {
						setIsHidden(1);
						activityhistory.setActivityTypeId(1);
						activityhistory.setIpAddress(ipaddress);
						activityhistory.setUserName(displayNameAddToHistory);
						activityhistory.setTopicId(topicId);
						activityhistory.setTitle(title_);
						activityhistory.setDistrictId(districtId_);
						dao.add(activityhistory);

						this.sameDistrict = dao.topicSameDistrict(districtId,
								topicId);
						this.recentView = dao.listRecentView(ipaddress);
						this.images = dao.image(topicId);
						this.universitiesList = dao.listUniversity(districtId);
						this.parksList = dao.listParks(districtId);
						this.markertsList = dao.listMarkets(districtId);
						this.rate = dao.getRate(topicId);
						this.busList = dao.listBus(districtId);
						this.provinces = dao.listProvinces();
					} else {
						return NONE;
					}
				}

				return SUCCESS;
			}
		}
	}

	public String reportSpam() {
		int userId_ = 0;
		String displayNamess = "";
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userIdss")) {
			userId_ = (Integer) session.get("userIdss");
			setUserId(userId_);
			displayNamess = (String) session.get("displayNamess");
		}

		reportSpam.setDescription(decodeURIComponent(spamdescreption));
		reportSpam.setUsersId(userId);
		reportSpam.setTopicId(topicId);
		adddao.reportSpam(reportSpam);
		this.email = dao.getEmail(topicId);
		for (Iterator iterator1 = email.iterator(); iterator1.hasNext();) {
			Object[] employee = (Object[]) iterator1.next();

			send.send_Email(employee[1].toString(),
					"Bài đăng " + employee[0].toString()
							+ " Của bạn đã được thành viên báo cáo với nội dung !", decodeURIComponent(spamdescreption));
		}
		execute();
		return SUCCESS;

	}
	public static String decodeURIComponent(String encodedURI) {
		char actualChar;

		StringBuffer buffer = new StringBuffer();

		int bytePattern, sumb = 0;

		for (int i = 0, more = -1; i < encodedURI.length(); i++) {
			actualChar = encodedURI.charAt(i);

			switch (actualChar) {
			case '%': {
				actualChar = encodedURI.charAt(++i);
				int hb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				actualChar = encodedURI.charAt(++i);
				int lb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				bytePattern = (hb << 4) | lb;
				break;
			}
			case '+': {
				bytePattern = ' ';
				break;
			}
			default: {
				bytePattern = actualChar;
			}
			}

			if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx
				sumb = (sumb << 6) | (bytePattern & 0x3f);
				if (--more == 0)
					buffer.append((char) sumb);
			} else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
				buffer.append((char) bytePattern);
			} else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
				sumb = bytePattern & 0x1f;
				more = 1;
			} else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
				sumb = bytePattern & 0x0f;
				more = 2;
			} else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx
				sumb = bytePattern & 0x07;
				more = 3;
			} else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx
				sumb = bytePattern & 0x03;
				more = 4;
			} else { // 1111110x
				sumb = bytePattern & 0x01;
				more = 5;
			}
		}
		return buffer.toString();
	}
	public String getStrDate() {
		String curdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(Calendar.getInstance().getTime());
		return curdate;
	}

	public List<Object> getDetailsList() {
		return detailsList;
	}

	public void setDetailsList(List<Object> detailsList) {
		this.detailsList = detailsList;
	}

	public int getTopicId() {
		return topicId;
	}

	public void setTopicId(int topicId) {
		this.topicId = topicId;
	}

	public List<Topics> getSameDistrict() {
		return sameDistrict;
	}

	public void setSameDistrict(List<Topics> sameDistrict) {
		this.sameDistrict = sameDistrict;
	}

	public int getDistrictId() {
		return districtId;
	}

	public void setDistrictId(int districtId) {
		this.districtId = districtId;
	}

	public List<Topicimages> getImages() {
		return images;
	}

	public void setImages(List<Topicimages> images) {
		this.images = images;
	}

	public int getIsOwner() {
		return isOwner;
	}

	public void setIsOwner(int isOwner) {
		this.isOwner = isOwner;
	}

	public int getIsAdmin() {
		return isAdmin;
	}

	public void setIsAdmin(int isAdmin) {
		this.isAdmin = isAdmin;
	}

	public Activityhistorys getActivityhistory() {
		return activityhistory;
	}

	public void setActivityhistory(Activityhistorys activityhistory) {
		this.activityhistory = activityhistory;
	}

	public List<Object> getUniversitiesList() {
		return universitiesList;
	}

	public void setUniversitiesList(List<Object> universitiesList) {
		this.universitiesList = universitiesList;
	}

	public List<Object> getMarkertsList() {
		return markertsList;
	}

	public void setMarkertsList(List<Object> markertsList) {
		this.markertsList = markertsList;
	}

	public List<Object> getParksList() {
		return parksList;
	}

	public void setParksList(List<Object> parksList) {
		this.parksList = parksList;
	}

	public List<Object> getBusList() {
		return busList;
	}

	public void setBusList(List<Object> busList) {
		this.busList = busList;
	}

	public List<Object> getRate() {
		return rate;
	}

	public void setRate(List<Object> rate) {
		this.rate = rate;
	}

	public List<Object> getRecentView() {
		return recentView;
	}

	public void setRecentView(List<Object> recentView) {
		this.recentView = recentView;
	}

	public List<Provinces> getProvinces() {
		return provinces;
	}

	public void setProvinces(List<Provinces> provinces) {
		this.provinces = provinces;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public int getRateValue() {
		return rateValue;
	}

	public void setRateValue(int rateValue) {
		this.rateValue = rateValue;
	}

	public Ratetopics getRateTopic() {
		return rateTopic;
	}

	public void setRateTopic(Ratetopics rateTopic) {
		this.rateTopic = rateTopic;
	}

	public Reportspams getReportSpam() {
		return reportSpam;
	}

	public void setReportSpam(Reportspams reportSpam) {
		this.reportSpam = reportSpam;
	}

	public String getSpamdescreption() {
		return spamdescreption;
	}

	public void setSpamdescreption(String spamdescreption) {
		this.spamdescreption = spamdescreption;
	}

	public int getIsHidden() {
		return isHidden;
	}

	public void setIsHidden(int isHidden) {
		this.isHidden = isHidden;
	}

	public List<Object> getEmail() {
		return email;
	}

	public void setEmail(List<Object> email) {
		this.email = email;
	}

}
